﻿using AutoMapper;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using BW.MesProject.WareHouse.Infrastructure;
using BW.MesProject.WareHouse.Infrastructure.Dto.Input;
using BW.MesProject.WareHouse.Infrastructure.Dto.OutPut;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BW.MesProject.WareHouse.Application
{
    /// <summary>
    /// 人员信息
    /// </summary>
    public class EMPServices : IEMPServices
    {
        private readonly IBaseRepository<EMPModel> _Emp;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="Emp"></param>
        /// <param name="mapper"></param>
        public EMPServices(IBaseRepository<EMPModel> Emp, IMapper mapper)
        {
            _Emp = Emp;
            this._mapper = mapper;
        }


        /// <summary>
        /// 查询人员
        /// </summary>
        /// <param name="WareName"></param>
        /// <returns></returns>
        public ApiResult<List<EMPModel>> GetEMP(string? EmpName, int pagesize, int pageNum,string DepId)
        {
            try
            {
                int totalCount = 0;
                //查询名称来显示数据
                var list = _Emp.GetAll().Where(x => x.JobCode != null);
                List<EMPModel> Emplist = new List<EMPModel>();
                if (pagesize == 0)
                {
                    // 不分页，仅按名称筛选
                    if (EmpName != null)
                    {    
                        Emplist = list.LeftJoin<JobModel>((a, b) => a.JobCode == b.JobId).Where(a => a.EMPName.Contains(EmpName) && a.DEPCODE== DepId && a.IsEnable == true).OrderBy(a => new {a.CreatedTime, a.EMPID }).ToList();
                    }
                    else
                    {
                        Emplist = list.LeftJoin<JobModel>((a, b) => a.JobCode == b.JobId).Where(a =>  a.DEPCODE == DepId && a.IsEnable == true).OrderBy(a => new { a.CreatedTime, a.EMPID }).ToList();
                    }
                }
                else
                {
                    if (EmpName != null)
                    {
                        Emplist = list.LeftJoin<JobModel>((a, b) => a.JobCode == b.JobId).Where(a => a.EMPName.Contains(EmpName) && a.DEPCODE == DepId).OrderBy(a => new { a.CreatedTime, a.EMPID }).ToPageList(pageNum, pagesize, ref totalCount).ToList();
                    }
                    else
                    {
                        Emplist = list.LeftJoin<JobModel>((a, b) => a.JobCode == b.JobId).Where(a => a.DEPCODE == DepId).OrderBy(a => new {a.CreatedTime,a.EMPID }).ToPageList(pageNum, pagesize, ref totalCount).ToList();
                    }


                }
                var queryList = Emplist?.ToList();
                return new ApiResult<List<EMPModel>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = totalCount,
                    PageNum = pageNum,
                    PageSize = pagesize
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询人员信息时发生异常: {ex.Message}");
                return new ApiResult<List<EMPModel>>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new List<EMPModel>(),
                    TotalCount = 0,
                    PageNum = pageNum,
                    PageSize = pagesize
                };
            }
            
        }


        /// <summary>
        /// 查询人员新
        /// </summary>
        /// <param name="qryInput"></param>
        /// <returns></returns>
        public ApiResult<List<EMPOut>> GetEMPNew(QryInput qryInput)
        {
            try
            {
                int totalCount = 0;

                // 获取所有库位
                var list = _Emp.GetAll();


                if (qryInput.PageSize == 0)
                {

                    list = list.OrderBy(u => u.CreatedTime);
                }
                else
                {

                    // 按编码查询
                    if (!string.IsNullOrEmpty(qryInput.QryID) && !string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.EMPID.Contains(qryInput.QryID) && x.EMPName.Contains(qryInput.QryName));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryID))
                    {
                        list = list.Where(x => x.EMPID.Contains(qryInput.QryID));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.EMPName.Contains(qryInput.QryName));
                    }


                }
                // 处理结果数据
                var result = new List<EMPOut>();

                //链表查询
                var query1 = list.LeftJoin<JobModel>((a, b) => a.JobCode == b.JobId).LeftJoin<DEPModel>((a, b,c) => a.DEPCODE == c.DepId).Select((a, b,c) =>
                    new EMPOut
                    {
                        EMPID=a.EMPID,
                        EMPName=a.EMPName,
                        EMpEmail=a.EMpEmail,
                        IdCard=a.IdCard,
                        Phone=a.Phone,
                        CreatedTime=a.CreatedTime,
                        UpdatedTime=a.UpdatedTime,
                        IsDeleted=a.IsDeleted,
                        IsEnable=a.IsEnable,
                        CreatedBy=a.CreatedBy,
                        JobCode=a.JobCode,
                        JobName=b.JobName,
                        DEPCODE=a.DEPCODE,
                        DEPNAME=c.DepName
                    });

                //获取集合
                var queryList = query1?.ToList();


                // 分页处理
                if (qryInput.PageSize > 0)
                {
                    queryList = queryList
                        .OrderByDescending(x => x.CreatedTime)
                        .Skip((qryInput.PageNum - 1) * qryInput.PageSize)
                        .Take(qryInput.PageSize)
                        .ToList();
                }

                return new ApiResult<List<EMPOut>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = query1.ToList().Count,
                    PageNum = qryInput.PageNum,
                    PageSize = qryInput.PageSize
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询人员信息时发生异常: {ex.Message}");
                return new ApiResult<List<EMPOut>>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new List<EMPOut>(),
                    TotalCount = 0,
                    PageNum = qryInput.PageNum,
                    PageSize = qryInput.PageSize
                };
            }

        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="EMP"></param>
        /// <returns></returns>
        public ApiResult<int> AddEMP(EMPModel EMP)
        {
            try
            {
                //判断人员编码，名称是否为空
                if (string.IsNullOrEmpty(EMP.EMPID) || string.IsNullOrEmpty(EMP.EMPName))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "请检查人员编码，名称是否为空"
                    };
                }
                var model = _Emp.GetValue(x => x.EMPID == EMP.EMPID);
                if (model != null && !string.IsNullOrEmpty(model.EMPID))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "人员编号重复，请重新检查修改！！！"
                    };
                }

                //添加
                var models = _mapper.Map<EMPModel>(EMP);

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Message = "添加成功",
                    Data = _Emp.Add(EMP),
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"添加人员时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"添加失败: {ex.Message}",
                    Data = 0,
                    TotalCount = 0
                };
            }
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateEMP(EMPModel model)
        {
            try
            {
                //根据id查询是否有这条数据没有就修改不了
                var query = _Emp.GetValue(x => x.EMPID == model.EMPID);
                if (query == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "修改失败，未找到指定的工艺分类信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }

                //保存添加人和添加时间，添加修改人和修改时间
                _Emp.Update(model);

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "修改成功",
                    Data = 1,
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"修改工艺分类时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 修改启用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateEnable(EMPModel model)
        {
            var IsEnable = model.IsEnable;
            //根据id修改逻辑删除为 false
            model = _Emp.GetValue(x => x.EMPID == model.EMPID);
            model.IsEnable = IsEnable;
            var Message = string.Empty;
            if (IsEnable)
            {
                Message = "启用成功";
            }
            else
            {
                Message = "停用成功";
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = Message,
                Data = _Emp.Update(model),
                TotalCount = 0
            };

        }

        /// <summary>
        /// 软删除（修改状态）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateDelete(string Id)
        {
            //根据id修改逻辑删除为 false
            var model = _Emp.GetValue(x => x.EMPID == Id);
            model.IsDeleted = true;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = _Emp.Update(model),
                TotalCount = 0
            };
        }

        /// <summary>
        /// 查询表是否有该编码
        /// </summary>
        /// <param name="EMPID"></param>
        /// <returns></returns>
        public ApiResult<int> GetEMPID(string EMPID)
        {
            var model = _Emp.GetValue(x => x.EMPID == EMPID);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "成功",
                Data = 1,
                TotalCount = 0
            };

        }
    }
}
